#coding:utf-8
import apiBussiness
import apiGrequests
# from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
import datetime,json

# scheduler = BlockingScheduler()
scheduler = BackgroundScheduler()

def schedulerRunCase(plan):

    #   根据项目、模块，或者用例去执行相关的case
    caseIdList = []
    print(plan.get('api_plan_name'))
    print(plan.get('caseIdList'))
    if plan.get('caseIdList') != '':
        #   直接运行caseId
        print('==============================================')
        case = plan.get('caseIdList').split(',')
        if case:
            caseIdList = case
    else:
        print('--------------------')
        caseIdList = apiBussiness.case_api_all(plan.get('project_id'),plan.get('module_id'))
        # print(caseIdList)
    for caseId in caseIdList:

        apiGrequests.runApi(caseId, planId=plan.get('id'))

def is_json_dump(content):
    try:
        return json.dumps(content)
    except:
        return False

@scheduler.scheduled_job('cron', hour=9)
def run_job():
    #每一个任务就创建一个调度器
    allPlans = apiBussiness.case_api_plan_all()
    for plan in allPlans:
        order = plan.get('auto_order')
        if order == "":
            #   如果为空，表示是一个立即只执行1次的任务
            scheduler.add_job(schedulerRunCase,
                              args=(plan,),
                              name=plan.get('api_plan_name'),
                              trigger='date',
                              next_run_time=datetime.datetime.now())
        elif 'cron' in order:
            orderTime = order.split(':')
            if len(orderTime)>0:
                orderTime = int(orderTime[1])
                #   否则为一个定时任务，每天几点钟执行
                scheduler.add_job(schedulerRunCase,
                                  args=(plan,),
                                  name=plan.get('api_plan_name'),
                                  trigger='cron',
                                  hour=orderTime,minutes ='*')
        elif 'interval' in order:
            orderTime = order.split(':')
            if len(orderTime) > 0:
                orderTime = int(orderTime[1])
                #   否则为一个定时任务，每天几点钟执行
                scheduler.add_job(schedulerRunCase,
                                  args=(plan,),
                                  name=plan.get('api_plan_name'),
                                trigger='interval', minutes =orderTime)

def back_runJob():
    run_job()
    scheduler.start()
